package com.videoshare.multimedia.dao;

import java.sql.*;

import javax.sql.*;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import java.util.*;

import com.sapientia.multimedia.*;
import com.sapientia.user.bean.User;
import com.sapientia.user.dao.TableFieldHandler;
import com.sapientia.user.dao.UserDAOImpl;
import com.sapientia.user.dao.BaseDAO;
import com.sapientia.rdfmodel.bean.DCFormatBean;

public class MultimediaDAOImpl extends BaseDAO implements MultimediaDAO 
{
	
	private static Log log = LogFactory.getLog(UserDAOImpl.class);
	
	/** datasource */
    private DataSource dataSource = null;
    
    /** connection */
    private Connection conn = null;

    /** costruttore, utilizza il datasource passato al costruttore come argomento */
    public MultimediaDAOImpl(DataSource dataSource)
    {
        this.dataSource = dataSource;
    }
    
    /** costruttore, utilizza la connessione passata al costruttore come argomento */
    public MultimediaDAOImpl(Connection conn)
    {
        this.conn = conn;
    }

	public MimeTypeBean getMimeType(){
		
		PreparedStatement pstmt = null;
        ResultSet rset = null;
        MimeTypeBean mimetypes = null;
        
        
        try {
            if( conn == null )
                conn = dataSource.getConnection();

            
            DatabaseMetaData dbmd = conn.getMetaData();
            
            
            int transactionIsolation = dbmd.getDefaultTransactionIsolation();
            String dbProductName = dbmd.getDatabaseProductName();
            String dbVersion = dbmd.getDatabaseProductVersion();
            String driverName = dbmd.getDriverName();
            String url = dbmd.getURL();
            String info = "Connect to the db " + dbProductName + " " +
			            " DB Version: " + dbVersion + 
			            " Driver: " + driverName +
			            " URL: " + url +
			            " Transaction Isolation: " + transactionIsolation;
            
            System.out.println(info);
            
            log.info(info);
            
            
            String query = "SELECT stream, type FROM mime_type";
            
            pstmt = conn.prepareStatement(query);
            
            rset = pstmt.executeQuery();
            
            mimetypes = makeBean(resultsetToList(rset));
            
            
            log.info("Got users data from the database.");
            
        } 
        catch(SQLException e) {
            e.printStackTrace();
            log.error("Cannot get data from the database");
        }
        finally {
            
            try 
            { 
                if( rset != null )
                    rset.close(); 
                
            }
            catch(Exception e) {
                System.out.println("Class MultimediaDAO, getMimeType() method call error..");
                e.printStackTrace();
                log.error("Cannot close the result set");
            }
            
            try 
            { 
                if( pstmt != null )
                    pstmt.close(); 
                
            }
            catch(Exception e) { 
                System.out.println("Class MultimediaDAO, getMimeType() method call error..");
                e.printStackTrace();
                log.error("Cannot close the prepared statement.");
            }
            
        }
        
        return mimetypes;
	
		
	}
	
	/**
     * Preleva i dati del result set contenuti in un oggetto List e li salva in un 
     * bean appropriato, facendo corrispondere un bean a ciascun record.
     * Restituisce una lista di bean
     */
    private MimeTypeBean makeBean(List rows)
    {
    	MimeTypeBean bean = new MimeTypeBean(); 
    	
    	List audioBeanList = new ArrayList();
    	List videoBeanList = new ArrayList();
    	
        ListIterator rowIterator = rows.listIterator();
        int rowcounter = 0;
        while(rowIterator.hasNext())
        {
            rowcounter++;
            List fieldlist = (List)rowIterator.next();
            ListIterator fieldsIterator = fieldlist.listIterator();
            Object obj = null;
            String type = "";
            String columnName = "";                        
            
           
            String streamType = "";
            String mimeType = "";
            DCFormatBean audiostream = new DCFormatBean();
            DCFormatBean videostream = new DCFormatBean();
            
            while(fieldsIterator.hasNext())
            {
                TableFieldHandler tfhandler = (TableFieldHandler)fieldsIterator.next();
                obj = tfhandler.getObject();
                type = tfhandler.getType();
                columnName = tfhandler.getColumnName().trim();                               
                
                if( columnName.equalsIgnoreCase("STREAM") )
                {                    
                	streamType =  (String)obj;                	                                  
                }                
                if( columnName.equalsIgnoreCase("TYPE") )
                {                    
                	mimeType =  (String)obj;                	
                }
                                              
            }
            
            if(streamType.equalsIgnoreCase("audio"))
            {
            	audiostream.setAudioStreamMimeType(mimeType);
            	audioBeanList.add(audiostream);
            }
            else
            {
            	videostream.setVideoStreamMimeType(mimeType);
            	videoBeanList.add(videostream);
            }
            
         }
        
        bean.setAudioStreamMimeTypeList(audioBeanList);
        bean.setVideoStreamMimeTypeList(videoBeanList);
        
        return bean;
        
    }
	
}
